package cn.kai.process.chain;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import cn.kai.process.Process;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 执行结构 CompletableFuture 责任链 自动设置子线程request
 * Author: cKnight
 * Date: 2024/6/23
 */
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class CFRunChain extends AbstractChain<CompletableFuture<Void>>{
    /**
     * 必须指定线程池
     */
    private Executor executor;

    /**
     * 自动添加子线程request
     */
    private RequestAttributes requestAttributes;

    public CFRunChain(List<CompletableFuture<Void>> cfList,Executor executor){
        setElement(cfList);
        this.executor = executor;
        this.requestAttributes = RequestContextHolder.getRequestAttributes();
    }


    /**
     * 开始节点
     * @param executor
     * @return
     */
    public static CFRunChain start(Executor executor){
        return new CFRunChain(new ArrayList<>(),executor);
    }

    /**
     * 执行方法
     * @param process
     * @return
     */
    public CFRunChain next(Process process){
        getElements().add(
                CompletableFuture.runAsync(()->{
                    //设置上下文信息
                    RequestContextHolder.setRequestAttributes(requestAttributes);
                    try {
                        //执行表达式
                        process.execute();
                    }finally {
                        // 重置上下文信息
                        RequestContextHolder.setRequestAttributes(null);
                    }

                },executor)
        );
        return this;
    }

    @Override
    public void end() {
        end(5L);
    }

    /**
     * 自定义超时时间 秒为单位
     * @param time
     */
    public void end(Long time) {
        try {
            CompletableFuture.allOf(getElements().toArray(new CompletableFuture[0])).get(time, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("CFRunChain 执行被中断", e);
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            log.error("CFRunChain 执行异常", e.getCause());
        } catch (TimeoutException e) {
            log.error("CFRunChain 执行超时", e);
        }
    }
}
